local class = select(2, UnitClass('player'))

if class ~= "HUNTER" then
	if class ~= "WARLOCK" then
		DisableAddOn("FuBar_PetFu")
		return
	end
end

local Tablet = AceLibrary("Tablet-2.0")
local CurrentPetHappiness = 3

PetFu = AceLibrary("AceAddon-2.0"):new("AceEvent-2.0", "FuBarPlugin-2.0", "AceDB-2.0", "AceConsole-2.0")
PetFu.hasIcon = true
PetFu:RegisterDB("PetFuDB")

local PetFu_BarHeight = 4

local PetFu_XPBar = CreateFrame("Frame", nil, UIParent)
PetFu_XPBar:SetFrameStrata("HIGH")
PetFu_XPBar:SetHeight(PetFu_BarHeight)
local tex = PetFu_XPBar:CreateTexture(nil,"HIGH")
tex:SetTexture("Interface\\AddOns\\FuBar_PetFu\\bar.tga")
tex:SetVertexColor(0,0,1,1)
tex:SetAllPoints(PetFu_XPBar)
PetFu_XPBar.texture = tex
PetFu_XPBar:SetPoint("BOTTOMLEFT", PetFu.frame, "BOTTOMLEFT")

local PetFu_Bar = CreateFrame("Frame", nil, UIParent)
PetFu_Bar:SetFrameStrata("MEDIUM")
PetFu_Bar:SetHeight(PetFu_BarHeight)
tex = PetFu_Bar:CreateTexture(nil,"HIGH")
tex:SetTexture("Interface\\AddOns\\FuBar_PetFu\\bar.tga")
tex:SetVertexColor(0.95,0.95,0.95,1)
tex:SetAllPoints(PetFu_Bar)
PetFu_Bar.texture = tex
PetFu_Bar:SetPoint("BOTTOMLEFT", PetFu.frame, "BOTTOMLEFT")

function PetFu:OnEnable()
	self.timeSinceLastUpdate = 0
	self:ScheduleRepeatingEvent(self.Update, 1, self)
	_, self.playerClass = UnitClass("player")
	if self.playerClass == "HUNTER" then
		self:RegisterEvent("PET_STABLE_CLOSED")
	end
end

function PetFu:UpdateText()
	local msg = ""
	local curXP, maxXP = GetPetExperience()

	if UnitExists("pet") then

		local Level = UnitLevel("pet");
		local cLevel = UnitLevel("player");
		if PetFu:IsShowingLevel() then
			msg = msg.."("..Level..") "
		end
		
		if PetFu:IsShowingName() then
			local petName = UnitName("pet")
			msg = msg..petName..": "
		end

		if self.playerClass == "HUNTER" then
			if cLevel ~= Level or (cLevel == Level and PetFu:IsShowingXPWhenNotLeveling()) then
				msg = msg..curXP.."/"..maxXP
				if PetFu:IsShowingPercent() then
					msg = msg.." ("..(floor(curXP/maxXP*100)).."%)"
				end
				if PetFu:IsShowingBar() then
					local PFW = PetFu.frame:GetWidth()
					PetFu_Bar:Show()
					if curXP > 0 then
						PetFu_XPBar:Show()
						PetFu_XPBar:SetWidth(PFW * curXP/maxXP)
						PetFu_XPBar:SetPoint("BOTTOMLEFT", PetFu.frame, "BOTTOMLEFT", 0, 3)
					end
					PetFu_Bar:SetWidth(PFW)
					PetFu_Bar:SetPoint("BOTTOMLEFT", PetFu.frame, "BOTTOMLEFT", 0, 3)
				else
					PetFu_XPBar:Hide()
					PetFu_Bar:Hide()
				end
			else
				PetFu_XPBar:Hide()
				PetFu_Bar:Hide()
			end
	
			local petHappiness, petDmgPcnt, petGainRate = GetPetHappiness();
			if petHappiness ~= nil and PetFu:IsShowingHappiness() then
			  msg = msg.." - "
				if petHappiness == 1 then
					msg = msg..format("|cffff0000%s|r", "Unhappy")
				end
				if petHappiness == 2 then
					msg = msg..format("|cffffff66%s|r", "Content")
				end
				if petHappiness == 3 then
					msg = msg..format("|cff00ff00%s|r", "Happy")
				end
			end
			
			if petHappiness ~= nil then
				if PetFu:IsPlayingSounds() then
					if petHappiness < CurrentPetHappiness then
						PlaySoundFile("Interface\\AddOns\\FuBar_PetFu\\decrease.wav")
					end
					if petHappiness > CurrentPetHappiness then
						PlaySoundFile("Interface\\AddOns\\FuBar_PetFu\\increase.wav")
					end
				end
				CurrentPetHappiness = petHappiness
			end
		else
			if UnitCreatureFamily("pet") ~= nil then
				msg = msg..UnitCreatureFamily("pet")
			end
		end
		
		local petIcon = GetPetIcon()
		if petIcon ~= nil then
			self:SetIcon(petIcon)
		end

	else
		msg = "No pet"
		PetFu_XPBar:Hide()
		PetFu_Bar:Hide()
	end
	
	self:SetText(msg)
end

PetFu.OnMenuRequest = {
	type = "group",
	handler = PetFu,
	args = {
		Pet_name = {
			type = "toggle",
			name = "Show Name",
			desc = "Show Name",
			get  = function() return PetFu:IsShowingName() end,
			set  = function() PetFu:ToggleShowingName() end,
		},
		Pet_level = {
			type = "toggle",
			name = "Show Level",
			desc = "Show Level",
			get  = function() return PetFu:IsShowingLevel() end,
			set  = function() PetFu:ToggleShowingLevel() end,
		},
		Pet_XP = {
			type = "toggle",
			name = "Show XP when not leveling",
			desc = "Show XP when your pet isn't earning XP (you are the same level)",
			get  = function() return PetFu:IsShowingXPWhenNotLeveling() end,
			set  = function() PetFu:ToggleShowingXPWhenNotLeveling() end,
		},
		Pet_percent = {
			type = "toggle",
			name = "Show XP Percent",
			desc = "Show XP Percent",
			get  = function() return PetFu:IsShowingPercent() end,
			set  = function() PetFu:ToggleShowingPercent() end,
		},
		Pet_happiness = {
			type = "toggle",
			name = "Show Happiness",
			desc = "Show Happiness",
			get  = function() return PetFu:IsShowingHappiness() end,
			set  = function() PetFu:ToggleShowingHappiness() end,
		},
		Pet_sounds = {
			type = "toggle",
			name = "Play Sounds",
			desc = "Play sounds on happiness increase/decrease",
			get  = function() return PetFu:IsPlayingSounds() end,
			set  = function() PetFu:TogglePlayingSounds() end,
		},
		Pet_bar = {
			type = "toggle",
			name = "Show XP Bar",
			desc = "Shows a bar below the text if the pet is earning XP",
			get  = function() return PetFu:IsShowingBar() end,
			set  = function() PetFu:ToggleShowingBar() end,
		},
	},
}

function PetFu:PET_STABLE_CLOSED()
	local _, petName, petLevel, _, _ = GetStablePetInfo(1);
	if petName ~= nil then
		self.db.char["Stabled1"] = "("..petLevel..") "..petName
	end
	-- DEFAULT_CHAT_FRAME:AddMessage(self.db.char["Stabled1"])
	
	_, petName, petLevel, _, _ = GetStablePetInfo(2);
	if petName ~= nil then
		self.db.char["Stabled2"] = "("..petLevel..") "..petName
	end
	
end

function PetFu:IsShowingName()
	return self.db.profile["ShowName"]
end

function PetFu:ToggleShowingName(loud)
	self.db.profile["ShowName"] = not self.db.profile["ShowName"]
	self:UpdateText()
	return self.db.profile["ShowName"]
end

function PetFu:IsShowingLevel()
	return self.db.profile["ShowLevel"]
end

function PetFu:ToggleShowingLevel(loud)
	self.db.profile["ShowLevel"] = not self.db.profile["ShowLevel"]
	self:UpdateText()
	return self.db.profile["ShowLevel"]
end

function PetFu:IsShowingXPWhenNotLeveling()
	return self.db.profile["ShowXPWhenNotLeveling"]
end

function PetFu:ToggleShowingXPWhenNotLeveling(loud)
	self.db.profile["ShowXPWhenNotLeveling"] = not self.db.profile["ShowXPWhenNotLeveling"]
	self:UpdateText()
	return self.db.profile["ShowXPWhenNotLeveling"]
end

function PetFu:IsShowingPercent()
	return self.db.profile["ShowPercent"]
end

function PetFu:ToggleShowingPercent(loud)
	self.db.profile["ShowPercent"] = not self.db.profile["ShowPercent"]
	self:UpdateText()
	return self.db.profile["ShowPercent"]
end

function PetFu:IsShowingHappiness()
	return self.db.profile["ShowHappiness"]
end

function PetFu:ToggleShowingHappiness(loud)
	self.db.profile["ShowHappiness"] = not self.db.profile["ShowHappiness"]
	self:UpdateText()
	return self.db.profile["ShowHappiness"]
end

function PetFu:OnClick()
	ToggleCharacter("PetPaperDollFrame")
end

function PetFu:IsPlayingSounds()
	return self.db.profile["PlaySounds"]
end

function PetFu:TogglePlayingSounds(loud)
	self.db.profile["PlaySounds"] = not self.db.profile["PlaySounds"]
	self:UpdateText()
	return self.db.profile["PlaySounds"]
end

function PetFu:IsShowingBar()
	return self.db.profile["ShowBar"]
end

function PetFu:ToggleShowingBar(loud)
	self.db.profile["ShowBar"] = not self.db.profile["ShowBar"]
	self:UpdateText()
	return self.db.profile["ShowBar"]
end


function PetFu:OnTooltipUpdate()
	if UnitExists("pet") then
		local petType = UnitCreatureFamily("pet")
		local totalTP, usedTP = GetPetTrainingPoints()
		local freeTP = totalTP - usedTP
		local atkSpeed = UnitAttackSpeed("pet")
		local atkRate = UnitAttackBothHands("pet")
		local lowDmg, hiDmg, offlowDmg, offhiDmg, posBuff, negBuff, percentMod = UnitDamage("pet");
		local DPS = (((lowDmg + hiDmg) * .5 + posBuff + negBuff) * percentMod) / atkSpeed;
		local petName = UnitName("pet");
		local petLevel = UnitLevel("pet");
		local petLoyalty = GetPetLoyalty();
		if petLoyalty ~= nil then
			local startP, endP = string.find(petLoyalty, ")")
			petLoyalty = string.sub(petLoyalty, startP + 1)
		end
		local petFood = ""
	  local PetFoodList = {GetPetFoodTypes()};
		if PetFoodList[1] ~= nil then
			local index, cnt;
			for index, cnt in pairs(PetFoodList) do
				if (PetFoodList[index] ~= nil) then	
					petFood = petFood..PetFoodList[index].."\r"
				end
			end
		end
		local baseArmor, effectiveArmor, petArmor, posBuff, negBuff = UnitArmor("pet")
		local petHappiness, petDmgPcnt, petGainRate = GetPetHappiness();
		local petLoyaltyRate = "Loyalty decreasing"
		if petGainRate > 0 then
			petLoyaltyRate = "Loyalty Increasing"
		end
		
		local cat = Tablet:AddCategory(
			'columns', 2,
			'child_textR', 1,
			'child_textG', 1,
			'child_textB', 0,
			'child_text2R', 1,
			'child_text2G', 1,
			'child_text2B', 1
		)
	
		cat:AddLine('text', "Name:",            'text2', petName)
		cat:AddLine('text', "Level:",           'text2', petLevel)
		cat:AddLine('text', "Pet Type:",        'text2', petType)
		cat:AddLine('text', "Armor",            'text2', "")
		cat:AddLine('text', "    Base",         'text2', baseArmor)
		cat:AddLine('text', "    Effective",    'text2', effectiveArmor)
		cat:AddLine('text', "    Full",         'text2', petArmor)
		cat:AddLine('text', "    Negative buff",'text2', negBuff)
		cat:AddLine('text', "    Positive buff",'text2', posBuff)
		cat:AddLine('text', "Attack Speed:",    'text2', ((floor(atkSpeed*10))/10))
		cat:AddLine('text', "Attack Rate:",     'text2', atkRate)
		cat:AddLine('text', "Expected DPS:",    'text2', ((floor(DPS*10))/10))
		if self.playerClass == "HUNTER" then
			cat:AddLine('text', "Damage Rate:",     'text2', petDmgPcnt.."%")
			cat:AddLine('text', "Loyalty:",         'text2', petLoyalty)
			cat:AddLine('text', "",                 'text2', petLoyaltyRate)
			cat:AddLine('text', "Training Points:", 'text2', freeTP.."/"..totalTP)
			cat:AddLine('text', "Diet:",     				'text2', petFood)
		end
		cat:AddLine('text', "Strength:",        'text2', UnitStat("pet", 1))
		cat:AddLine('text', "Agility:",         'text2', UnitStat("pet", 2))
		cat:AddLine('text', "Stamina:",         'text2', UnitStat("pet", 3))
		cat:AddLine('text', "Intellect:",       'text2', UnitStat("pet", 4))
		cat:AddLine('text', "Spirit:",          'text2', UnitStat("pet", 5))
		
		if self.playerClass == "HUNTER" then
			local _, petName, petLevel, _, _ = GetStablePetInfo(1);
			if petName ~= nil then
				self.db.char["Stabled1"] = "("..petLevel..") "..petName
			end
			if self.db.char["Stabled1"] ~= nil then
				cat:AddLine('text', "Stabled pet:", 'text2', self.db.char["Stabled1"])
			end
			
			_, petName, petLevel, _, _ = GetStablePetInfo(2);
			if petName ~= nil then
				self.db.char["Stabled2"] = "("..petLevel..") "..petName
			end
			if self.db.char["Stabled2"] ~= nil then
				cat:AddLine('text', "Stabled pet:", 'text2', self.db.char["Stabled2"])
			end
		end
	end
end
